interface Clourse {
    errorResult?: (msg: string) => any;
    successResult?: (file: File) => any;
}



/**
 * @description: 上传文件
 * @param {Array} checkType
 * @param {number} checkSize  kb多少
 * @return {*}
 */
const uploads = (checkType: Array<string> | string | undefined = undefined, checkSize: number | undefined = undefined, clourse?: Clourse | undefined) => {
    //在body中添加标签
    //添加div元素(在内存中)
    let divObj = document.createElement('input');
    divObj.type = "file";
    divObj.style.display = 'none';
    divObj.onchange = (file) => getFile(file, divObj, checkType, checkSize, clourse);
    document.body.appendChild(divObj);
    divObj.click();
}

const type: { [key: string]: Array<string> } = {
    'image': ['png', 'jpg', 'jpeg'],
    'excel':['xls','xlsx']
}

const getFile = (ev: Event, divObj: any, checkType: Array<string> | string | undefined, checkSize: number | undefined, clourse: Clourse | undefined) => {
    document.body.removeChild(divObj);
    const file = ((ev.target as HTMLInputElement).files as FileList)[0] as File;
    if (typeof checkType === "string") checkType = type[checkType] ? type[checkType] : [];
    checkType = typeof checkType === 'undefined' ? [] : checkType.map(item => item.toLowerCase());
    const fileType = file.name.split(".").pop()?.toLowerCase() as string;
    try {
        if (checkType.length > 0 && checkType.indexOf(fileType) === -1) throw '该文件必须为' + checkType.reduce((prev, cur) => prev + ',' + cur) + '类型';
        if (typeof checkSize !== "undefined" && file.size >= checkSize * 1024) throw '文件不得超过' + checkSize + 'kb';
        return typeof clourse !== 'undefined' && typeof clourse.successResult !== 'undefined' ? clourse.successResult(file) : file;
    } catch (err) {
        if (typeof clourse !== 'undefined' && typeof clourse.errorResult !== 'undefined') return clourse.errorResult(err as string)
        else throw err;
    }
}


export default uploads;